<template>
    <div>
        <el-dialog
            title="新增农场区域"
            :visible.sync="dialogVisible"
            width="880px"
        >
            <el-form ref="form" :model="form" label-width="120px" size="small">
                <el-form-item label="选择农场名称:" prop="name" >
                    <el-select v-model="form.farmId" placeholder="请选择" style="width: 100%;">
                        <el-option
                            v-for="item in farmList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="区域名称:" prop="name">
                    <el-input v-model="form.name" placeholder="请输入区域名称" ></el-input>
                </el-form-item>
                <el-form-item label="区域编号:" prop="sn">
                    <el-input v-model="form.sn" placeholder="请输入区域编号" ></el-input>
                </el-form-item>
                <el-form-item label="农场图片:" prop="image">
                    <el-upload
                        class="avatar-uploader"
                        :action="action"
                        :show-file-list="false"
                        :headers="{ Authorization: 'Bearer ' + token }"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 100%; height: 100%;">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>

                </el-form-item>
                <el-form-item label="区域范围:" prop="region">
                    <div :style="{width:'100%',height:'100%'}">
                        <baidu-map id="map" :style="{width:'100%',height:'320px'}" :center="{lng:109.07566,lat:35.4696}"
                                   :zoom="zoom" @ready="mapReady1">
                            <bm-polygon :path="polygonPath" stroke-color="blue"
                                        :stroke-opacity="0.5"
                                        :stroke-weight="2"
                                        :editing="true" @lineupdate="updatePolygonPath"/>
                        </baidu-map>
                    </div>
                </el-form-item>
                <el-form-item label="备注:" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel" size="small">取 消</el-button>
                <el-button type="primary" @click="onSubmit" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {mapState} from "vuex";
import {addFarmArea} from "@/index/api/index/adoption/farmArea/farmArea"
import {farmList} from "@/index/api/index/adoption/farm/farm"

export default {
    data() {
        return {
            dialogVisible: false,
            form: {
                farmId: null,
                name: "",
                sn: "",
                longitude1: "",
                latitude1: "",
                region: "",
                image: "",
                remark: "",
            },
            fileList: [],
            BMap: null,
            point: null,
            zoom: 3,
            polygonPath: [],
            center: [109.07566, 35.4696],
            imageUrl: '',
            farmList: []
        }
    },
    computed: {
        ...mapState(["token", "action"]),
    },
    components: {},
    mounted() {
        this.getData()
    },
    methods: {
        cancel() {
            this.dialogVisible = false;
            this.polygonPath = [];
            this.$refs["form"].resetFields();
            this.imageUrl = '';
            this.form.farmId = null
        },
        showDialog() {
            this.dialogVisible = !this.dialogVisible
        },
        onSubmit() {
            addFarmArea(this.form).then(res => {
                if (res.code == 200) {
                    this.dialogVisible = false;
                    this.$message({
                        message: res.message,
                        type: "success",
                    });
                    this.imageUrl = '';
                    this.$parent.getRegionList();
                    this.polygonPath = [];
                    this.$refs["form"].resetFields();
                } else {
                    this.$message({
                        message: res.message,
                        type: "error",
                    });
                }
            })
        },
        mapReady1({BMap, map}) {
            this.point = new BMap.Point(this.center[0], this.center[1]);
            map.centerAndZoom(this.point, 7)
            map.enableDragging();   // 启用地图拖拽
            map.enableScrollWheelZoom(); // 启用滚轮缩放
            this.map = map;
            this.BMap = BMap;
            map.addEventListener("click", (e) => {
                // 获取点击位置的经纬度
                this.form.longitude1 = e.point.lng;
                this.form.latitude1 = e.point.lat;
                this.addPolygonPoint();
            });
        },
        updatePolygonPath(e) {
            this.polygonPath = e.target.getPath()
        },
        addPolygonPoint() {
            this.polygonPath.push({lng: this.form.longitude1, lat: this.form.latitude1})
            this.form.region = JSON.stringify(this.polygonPath);
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            this.$message.success('上传成功')
            this.form.image = res.data.filePath
        },
        beforeAvatarUpload(file) {
            const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
            const isAllowedType = allowedTypes.includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isAllowedType) {
                this.$message.error('上传头像图片只能是 JPG、PNG 或 PDF 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }

            return isAllowedType && isLt2M;
        },
        getData() {
            farmList().then(res => {
                this.farmList = res.data.items
            })
        }
    }
}
</script>

<style lang="less" scoped>

.flex-container {
    display: flex;
    align-items: center; /* 垂直居中 */
    margin-top: 10px;
}

/deep/ .el-upload{
    width: 313px;
    height: 268px;
    border: 1px #e0e0e0 dashed;
    .el-icon-plus{
        line-height: 268px;
    }
}
</style>
